import {Component, EventEmitter, Output} from '@angular/core';
import {
    AlertController, IonicPage, LoadingController, NavController, NavParams, Platform,
    ToastController
} from 'ionic-angular';
import {FeeDetailPage} from "./fee-detail/fee-detail";
import {SystemService} from "../../service/SystemService";
import {UserManager} from "../../../framework/manager/UserManager";
import {AssistTabPage} from "../assist-tab/assist-tab";
import {Log} from "../../../framework/utils/Log";
import {BasePage} from "../../BasePage";
import {SLLocalStorageUtils} from "../../../framework/utils/SLLocalStorageUtils";
import {ApplyStoreSLS} from "../applyStoreSLS";
import {Utils} from "../../../framework/utils/Utils";

/**
 * Generated class for the ApplyInfoTabPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */


@Component({
    selector: 'page-apply-info-tab',
    templateUrl: 'apply-info-tab.html',
    providers: [SystemService]
})
export class ApplyInfoTabPage extends BasePage {
    private static TAG: string = 'ApplyInfoTabPage';
    @Output() childEvent = new EventEmitter<any>();
    private dataList: Array<any> = [];
    private zcsxId: string;
    private danjuId: string;
    private list: Array<any> = [];
    feeDetailsValArr: Array<any> = [];
    detailSumMoneyList: any = [];
    private _newArr: any;
    private _statusBool: boolean = false;
    applyMoney: any = 0;
    bxType: any;
    editBool: boolean;
    editInfo: any;
    moneyAppleBool:boolean;
    moneyAppleInfo:any;
    biaoZhunZhi:any=[];
    constructor(public navCtrl: NavController, public navParams: NavParams, public sys: SystemService, public platform: Platform,
                public loadingCtrl: LoadingController,
                public toastCtrl: ToastController,
                public alertCtrl: AlertController) {
        super(platform, loadingCtrl, toastCtrl, alertCtrl);
        this.zcsxId = this.navParams.data.sxId;
        //this.danjuId = UserManager.getInstance().user.djId;
        this.danjuId =this.navParams.data.danJuBH;

        this.bxType = navParams.data.bxType;
        this.editBool = this.navParams.data.editBool;
        this.editInfo = this.navParams.data.editInfo;
        this.moneyAppleBool = this.navParams.data.moneyAppleBool;
        this.moneyAppleInfo = this.navParams.data.moneyAppleInfo;
    }

    ngOnInit() {
        console.log('ngOnInit ApplyInfoTabPage');

    }

    async ionViewDidEnter() {
        if (!Utils.isNullOrUndefined(await SLLocalStorageUtils.getInstance().getAppleFee())) {
            this.applyMoney = await SLLocalStorageUtils.getInstance().getAppleFee();
        }
        if (UserManager.getInstance().user.zcId == this.zcsxId && ApplyStoreSLS.getInstance().applyInfoBool && !this.editBool) {
            this.dataList = ApplyStoreSLS.getInstance().applyDataList;
            this.list = ApplyStoreSLS.getInstance().applyList;
            this.feeDetailsValArr = ApplyStoreSLS.getInstance().applyFee;
            this.applyMoney = ApplyStoreSLS.getInstance().appleTotalFee;
        } else {
            this.getPayDetail();
        }
    }

    getPayDetail() {
        let data = {
            ZhiChuSXBH: this.zcsxId,
            DanJuBH: this.danjuId
        };
        this.sys.getPayDetail(data).subscribe((res: any) => {
            if (res.msgCode == '1' && res.list.length > 0) {
                ApplyStoreSLS.getInstance().applyInfoBool = true;
                this.dataList = res.list;
                this._newArr = JSON.parse(JSON.stringify(this.dataList));
                Log.printObj(ApplyInfoTabPage.TAG, 'result==', res);
                this.dataAction();
            }
        }, error => {
            this.showError('网络连接失败');
        })
    }

   /* async editDataAction() {
        this.dataAction();
        //this.editInfo.ZhiChuMX.reverse();
        this.editInfo.ZhiChuMX.map((ev, i) => {
            //this.list[i].MingCheng=ev.MingXiMC,
            this.list[i].JinE = ev.MingXiJE;
            if (this.dataList[i].hasOwnProperty('FeiYongMX') && this.dataList[i].FeiYongMX[0] != undefined) {
                this.dataList[i].FeiYongMX[0].map(v3 => {
                    if (ev.hasOwnProperty('FeiYongMX')) {
                        ev.FeiYongMX.map((ev1, m) => {
                            v3.Options.map(v4 => {
                                ev1.MingXiZ.map((v5, n) => {
                                    if (v4.Value == v5) {
                                        this.feeDetailsValArr[i].FeiYongMX[0][m].MingXiBH = v5;
                                        this.feeDetailsValArr[i].FeiYongMX[0][m].val = v4.Text;
                                    } else {
                                        this.feeDetailsValArr[i].FeiYongMX[0][m].val = v5;
                                    }
                                })
                            })
                        })
                    }
                })
            }
        })

    }*/
    moneyApplyDataFun(){
        this.list =[];
        this.dataList = this.moneyAppleInfo.data.ZCMXlist;
        Log.printObj(ApplyInfoTabPage.TAG,"资金申请单支出明细=====",this.dataList);

        this.dataList.map((value, index) => {
            this.list.push({
                MingCheng:value.ZCMXMingCheng,
                ZhiChuMXBH: value.ZCMXBianHao,
                JinE: value.ZCMXJinE,
                BiaoZhuFY: "",
                FeiYongMX: []
            });
        });

    }
    private tmpArr=[];
    dataAction() {
        this.list =[];
        this.dataList.map((value, index) => {
            this.list.push({
                MingCheng:value.MingCheng,
                ZhiChuMXBH: value.BianHao,
                JinE: value.JinE === '0.00' ? '0' : value.JinE,
                BiaoZhuFY: "",
                FeiYongMX: []
            });


            this.tmpArr.push({len:0});



            this.feeDetailsValArr.push({FeiYongMX: []});
            value.FeiYongMX.map((_v, _i) => {
                this.feeDetailsValArr[index].FeiYongMX.push([]);
                _v.map((_cValue, _cIndex) => {
                    this.list[index].FeiYongMX.push(
                        {
                            MingXiBH: _cValue.BianHao,
                            MingXiZ: [ _cValue.FeiYongMXZ]
                        }
                    );
                    this.feeDetailsValArr[index].FeiYongMX[_i].push({MingXiBH: _cValue.BianHao, val: _cValue.FeiYongMXZ});

                });
            });
        });
        console.log(this.feeDetailsValArr)

    }

    pre() {

        //this.childEvent.emit({'name': '报销申请', 'id': 0});
        UserManager.getInstance().user.zcId = this.zcsxId;
        this.dataStore();
        this.navCtrl.pop();
    }

    dataStore() {
        ApplyStoreSLS.getInstance().applyList = this.list;
        ApplyStoreSLS.getInstance().applyFee = this.feeDetailsValArr;
        ApplyStoreSLS.getInstance().appleTotalFee = this.applyMoney;
        ApplyStoreSLS.getInstance().applyDataList = this.dataList;
    }

    ionViewDidLeave() {
        this.dataStore();
        UserManager.getInstance().user.zcId = this.zcsxId;
    }

    async calc() {
        this._statusBool = false;
        this.list.forEach(value => {
            value.BiaoZhuFY = "";
            value.FeiYongMX.forEach(v => {
                v.MingXiZ.splice(0, v.MingXiZ.length);
            })
        });
        /* await this.feeDetailsValArr.forEach((v, i) => {
            v.FeiYongMX.forEach((value, index) => {
                for (let n = 0; n < value.length; n++) {
                    if (value[n].val == "") {
                        this.showError("填写的内容不完整");
                        this._statusBool = true;
                        break;
                    }
                }
            });
        });*/
        /* for(let i=0;i<this.feeDetailsValArr.length;i++){
             for(let n=0;n<this.feeDetailsValArr[i].FeiYongMX;n++){
                 for(let m=0;m<this.feeDetailsValArr[i].FeiYongMX[n].length;m++){

                 }
             }
         }*/
        if (this._statusBool) return;
        await this.feeDetailsValArr.forEach((v, i) => {
            v.FeiYongMX.forEach((value, index) => {
                value.forEach((_d, _ii) => {
                    this.list[i].FeiYongMX.forEach((v2, i2) => {
                        if (_d.MingXiBH === v2.MingXiBH) {
                            v2.MingXiZ.push(_d.val);
                        }
                    });
                })
            });
        });
       // Log.printObj(ApplyInfoTabPage.TAG, 'mongey Apple New List result==', this.list);

        await this.getDetailSumMoney(this.list);
    }

    next() {
        /*if(this.applyMoney ==0){
            this.showError('报销金额不能为0');
            return;
        }*/
        this.dataStore();
        this.navCtrl.push(AssistTabPage, {sxId: this.zcsxId,danJuBH: this.danjuId,editInfo:this.editInfo,editBool:this.editBool,moneyAppleBool:this.moneyAppleBool,moneyAppleInfo:this.moneyAppleInfo});
    }

    addFeeDetail(index) {
        if (this._newArr[index].FeiYongMX[0] != undefined) {
            this.tmpArr[index].len +=1;

            this.dataList[index].FeiYongMX.push( this._newArr[index].FeiYongMX[0]);
            this.feeDetailsValArr[index].FeiYongMX.push([]);
            this._newArr[index].FeiYongMX[0].map((v, i) => {
                this.feeDetailsValArr[index].FeiYongMX[this.tmpArr[index].len].push({
                    MingXiBH: v.BianHao,
                    val: ''
                });
            });
        }
    }
    minusFeeDetail(index){
        if (this.dataList[index].FeiYongMX.length>1) {

                this.dataList[index].FeiYongMX.splice(this.tmpArr[index].len,1);

                this.feeDetailsValArr[index].FeiYongMX.splice(this.tmpArr[index].len,1);
            this.tmpArr[index].len -=1;
        }
    }
    async getDetailSumMoney(data) {
        let num = 0;
        let _d: any = {ZhiChuXX: data};
        this.sys.getDetailSumMoney(_d).subscribe(async (res: any) => {
            if (res.msgCode == '1') {

                this.detailSumMoneyList = res;
                Log.printObj(ApplyInfoTabPage.TAG, "detailSumMoneyList result == ", this.detailSumMoneyList);
                if(!this.editBool){
                    this.list.map((v, i) => {
                        res.ZhiChuMX.forEach(v3 => {
                            num = 0;
                            if (v.ZhiChuMXBH == v3.ZhiChuMXBH) {
                                console.log(v.ZhiChuMXBH,v3.ZhiChuMXBH)
                                v.JinE = v3.ZhiChuMXZJE != '0' ? v3.ZhiChuMXZJE : '';
                                v3.list.forEach(m => {
                                    num += Number(m);
                                    v.BiaoZhuFY = num;
                                })
                            }
                        });
                    });
                }

                let tempFee: number = 0;//计算报销总金额
               // Log.printObj(ApplyInfoTabPage.TAG, 'new List result=========1', this.list);

                await this.list.forEach(value => {
                    tempFee += this.delcommafy(value.JinE);
                });
                this.applyMoney = tempFee;
                Log.printObj(ApplyInfoTabPage.TAG, 'new List result==', this.list);

                await SLLocalStorageUtils.getInstance().setAppleFee(this.applyMoney);
                try {
                    await SLLocalStorageUtils.getInstance().setApplyDetails(this.list);

                } catch (error) {
                    Log.printObj(ApplyInfoTabPage.TAG, "next error == ", error);
                    throw error;
                }
                this.next();

            } else {
                this.showError(res.msg.split(':')[1]);

            }
        }, error => {
            this.showError('网络连接失败');

        });


    }
    switchType(){
        this.list.forEach(value => {
            value.FeiYongMX.forEach(v => {
                v.MingXiZ.splice(0, v.MingXiZ.length);
            })
        });

         this.feeDetailsValArr.forEach((v, i) => {
            v.FeiYongMX.forEach((value, index) => {
                value.forEach((_d, _ii) => {
                    this.list[i].FeiYongMX.forEach((v2, i2) => {
                        if (_d.MingXiBH === v2.MingXiBH) {
                            v2.MingXiZ.push(_d.val);
                        }
                    });
                })
            });
        });
        let _d: any = {ZhiChuXX: this.list};
        this.sys.getDetailSumMoney(_d).subscribe(async (res: any) => {
            if (res.msgCode == '1') {
                this.biaoZhunZhi = res.ZhiChuMX;
                Log.printObj(ApplyInfoTabPage.TAG, "biaoZhunZhi result == ", this.biaoZhunZhi);
            }
        })
    }

    delcommafy(num) {
        num = num.toString();
        num = num.replace(/[ ]/g, "");//去除空格  
        num = num.replace(/,/gi, '');
        return Number(num);
    }

}

